package gate;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;

import master.MasterInterface;
import sr.logger.Logger;
import util.Tuple;
import client.remote.ClientReceiver;
import gate.IGateEx;
import gate.ServerPackage;


public class Gate implements IGateEx
{
	Logger logger = Logger.getLogger(this.getClass());
	List<MasterInterface> servers = new ArrayList<MasterInterface>();
	MasterInterface currentActiveServer;
	ServerPackage serverPackage = ServerPackage.getServerPackage();
	@Override
	public synchronized MasterInterface getServer() throws RemoteException
	{
		logger.log("getServer");
		if(currentActiveServer == null)
		{
			getNewServer();
		}			
		return currentActiveServer;
	}
	private void getNewServer() throws RemoteException
	{
		while(currentActiveServer == null && !servers.isEmpty())
		{
			System.err.println("getting new server");
			try
			{
				MasterInterface tmpServer = servers.remove(0);
				//tmpServer.statusCheck();
				tmpServer.build(serverPackage,logger.log("getNewServer"));
				currentActiveServer = tmpServer;
			}
			catch(Exception e)
			{
				e.printStackTrace();
				System.out.println("Server Down");
			}
		}
		if(currentActiveServer == null)
			 throw new RemoteException("no more servers");
	}
	@Override
	public synchronized Tuple<Boolean, MasterInterface> isDown(
			MasterInterface currentInterface) throws RemoteException
	{

		try
		{
			currentActiveServer.statusCheck(logger.log("statusCheck"));
			if(!currentActiveServer.equals(currentInterface))
			{
				return new Tuple<Boolean,MasterInterface>(true,currentActiveServer);
			}
			return new Tuple<Boolean, MasterInterface>(false,null);
		} catch (RemoteException e)
		{
			System.err.println("CurrentServer Down");
			currentActiveServer = null;
		}
		getNewServer();
		return new Tuple<Boolean,MasterInterface>(true,currentActiveServer);
	}
	

	@Override
	public void newGameStarted(ArrayList<Long> clients, int roomId)
	{
		serverPackage.createRoom(roomId, clients);
		
	}

	@Override
	public void clientLeftGame(int roomId,long clientId)
	{
		serverPackage.clientLeftRoom(roomId, clientId);
	}

	@Override
	public void gameEnded(int roomId)
	{
		serverPackage.gameEnded(roomId);
		
	}

	@Override
	public void registerServer(MasterInterface master)
	{
		logger.log("RegisterServer");
		servers.add(master);
	}

	@Override
	public void clientEntered(Long clientId, ClientReceiver client)
	{
		serverPackage.addClient(clientId, client);
	}

	@Override
	public void clientLeft(long clientId)
	{
		serverPackage.removeClient(clientId);
		
	}

	

}
